package utils

import (
	"errors"
	"github.com/dgrijalva/jwt-go"
	"time"
	"wall/app/config"
)

/*封装JWT接口
 *Auth 发布签名
 *Parse 解析签名
 */

type JWT struct {
}

func (J JWT) Auth(userName string, userID string, Type int) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"iss":       "wifi",
		"exp":       time.Now().Add(time.Hour * 12).Unix(),
		"iat":       time.Now().Unix(),
		"user_name": userName,
		"user_id":   userID,
		"type":      Type,
	})

	tokenString, err := token.SignedString([]byte(config.Config.Web.Secret))
	if err != nil {
		return "", errors.New("token-fail-generated")
	}

	return tokenString, nil
}

/**
返回的参数中第一个为用户ID
第二个为用户名
第三个为用户类型
*/
func (J JWT) Parse(tokenString string, secret string) (interface{}, interface{}, interface{}, error) {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		return []byte(secret), nil
	})

	if err != nil {
		return nil, nil, nil, errors.New("token-broken")
	}

	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		return claims["user_id"], claims["user_name"], claims["type"], nil
	} else {
		return nil, nil, nil, errors.New("token-expired")
	}
}
